package com.shopping_back.util;

import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;

@Component
public class SensitiveWordFilter {

    private final Set<String> badWords = new HashSet<>();

    @PostConstruct
    public void init() {
        try (InputStream in = getClass().getClassLoader().getResourceAsStream("sensitive-words.txt")) {
            if (in == null) {
                System.err.println("[SensitiveWordFilter] 未找到 sensitive-words.txt，敏感词过滤失效");
                return;
            }
            try (BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) {
                br.lines()
                        .map(String::trim)
                        .filter(s -> !s.isEmpty() && !s.startsWith("#"))
                        .forEach(badWords::add);
            }
            System.out.println("[SensitiveWordFilter] 已加载敏感词 " + badWords.size() + " 个");
        } catch (Exception e) {
            System.err.println("[SensitiveWordFilter] 敏感词加载失败: " + e.getMessage());
        }
    }

    public boolean hasBadWord(String text) {
        if (text == null) return false;
        String normalized = text.replaceAll("[\\s\\p{Punct}　，。！？；：“”‘’]", "").toLowerCase();
        return badWords.stream().anyMatch(normalized::contains);
    }
} 